package com.ld.zxw.update;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;

import com.ld.zxw.Documents.Documents;
import com.ld.zxw.config.Config;
import com.ld.zxw.util.CommonUtil;
@SuppressWarnings("all")
public class UpdateIndex {

	private Logger log = Logger.getLogger(UpdateIndex.class);
	
	public static Config config = null;

	/**
	 * 更新索引
	 * @param list
	 * @throws IOException
	 */
	public boolean Index(List<HashMap> list){
		boolean flag = false;
		for (HashMap hashMap : list) {
			boolean index = Index(hashMap);
			if(!index){
				log.error("更新失败[]:"+hashMap);
			}else{
				flag = true;
			}
		}
		return flag;
	}


	/**
	 * 更新索引
	 * @param obj
	 * @throws IOException
	 */
	public boolean Index(HashMap hashMap){
		boolean flag =true;
		IndexWriter writer = null;
		try {
			writer = CommonUtil.getIndexWriter(config);

			Documents doc = new Documents();
			Iterator iterator = hashMap.entrySet().iterator();
			String id=null;
			while (iterator.hasNext()) {
				Map.Entry entry = (Map.Entry) iterator.next();
				doc.put(entry.getKey(), entry.getValue());
				if(entry.getKey().equals("id")){
					id=entry.getValue().toString();
				}
			}
			if(id != null){
				writer.updateDocument(new Term("id",id), doc.getDocument());
			}
			writer.commit();
		} catch (Exception e) {
			flag =false;
			log.error("更新索引-error:",e);
		}finally {
			CommonUtil.colseIndexWriter(writer);
		}
		return flag;
	}



}
